<template>
    <div class="slider-wrapper">
        <h2>1-100之间{{ num }}</h2>
        <h2>5-15之间{{ 5 + num / 100 * (15 - 5) }}</h2>
        <div class="slider" @click.self="onClick">
            <div
            :style="{ 'left': num + '%', 'transition': isTouch ? 'none' : '.3s'}"
            @touchstart.prevent="onStart"
            @touchmove.prevent="onMove"
            @touchend.prevent="onEnd"
            @touchcancel.prevent="onEnd"
            >
            </div>
        </div>
    </div>
</template>

<script>
export default {
  data() {
    return {
      num: 0,
      startNum: 0,  // 拖动开始 num 的值
      startX: 0, // 滑块的初始位置
      endX: 0, // 滑块的结束位置
      isTouch: false  // 是否正在拖动
    }
  },
  methods: {
    onClick(event) {
        console.log(event.offsetX)
        this.num = event.offsetX / 200 * 100
    },
    setNum() {
        const limit = n => Math.max(0, Math.min(100, n));
        this.num = limit(Math.round(this.startNum + 100 * (this.endX - this.startX) / 200));
    },
    onStart(event) {
      this.isTouch = true;
      console.log(event)
      const point = event.touches[0];
      this.startX = point.clientX;
      this.startNum = this.num;
    },
    onMove(event) {
      console.log(event)
      const point = event.touches[0];
      this.endX = point.clientX;
      this.setNum();
    },
    onEnd(event) {
      this.isTouch = false;
      this.endX = event.changedTouches[0].clientX;
      this.setNum();
    }
  }
}
</script>

<style lang="sass">
.slider
  width: 200px
  height: 50px
  position: relative
  margin: 0 auto
  &::before
    content: ""
    width: 100%
    height: 3px
    position: absolute
    left: 0
    top: 50%
    background: #ccc
    transform: translateY(-50%)
  div
    position: absolute
    width: 30px
    height: 30px
    border-radius: 50%
    background: #fff
    box-shadow: 0 0 5px 0 #ccc
    top: 10px
    left: 0px
    margin-left: -15px
    // transition: .6s
</style>
